<template>
  <view class="employee-management-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">员工管理</block>
      <block slot="right">
        <text class="cuIcon-add" @click="addEmployee"></text>
      </block>
    </cu-custom>

    <!-- 统计概览 -->
    <view class="stats-overview margin-top bg-white">
      <view class="stats-grid padding">
        <view class="stat-item" @click="filterByStatus('all')">
          <view class="stat-number text-blue">{{ employeeStats.total }}</view>
          <view class="stat-label">总员工</view>
        </view>
        <view class="stat-item" @click="filterByStatus('working')">
          <view class="stat-number text-green">{{ employeeStats.working }}</view>
          <view class="stat-label">工作中</view>
        </view>
        <view class="stat-item" @click="filterByStatus('idle')">
          <view class="stat-number text-orange">{{ employeeStats.idle }}</view>
          <view class="stat-label">空闲</view>
        </view>
        <view class="stat-item" @click="filterByStatus('leave')">
          <view class="stat-number text-gray">{{ employeeStats.leave }}</view>
          <view class="stat-label">请假</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-filter margin-top bg-white">
      <view class="search-bar padding">
        <view class="search-input-wrapper">
          <input v-model="searchKeyword" 
                 placeholder="搜索员工姓名或工号" 
                 class="search-input" 
                 @input="onSearch" />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>
      <view class="filter-tabs padding-lr">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tab-list">
            <view v-for="tab in filterTabs" :key="tab.value"
                  class="filter-tab" 
                  :class="{ active: currentFilter === tab.value }"
                  @click="changeFilter(tab.value)">
              {{ tab.label }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 员工列表 -->
    <view class="employee-list margin-top">
      <view v-for="employee in filteredEmployees" :key="employee.id" 
            class="employee-item bg-white margin-bottom" 
            @click="viewEmployeeDetail(employee)">
        <view class="employee-header padding">
          <view class="flex align-center">
            <image :src="employee.avatar || '/static/images/default-avatar.png'" 
                   class="employee-avatar margin-right"></image>
            <view class="flex-sub">
              <view class="employee-name">{{ employee.name }}</view>
              <view class="employee-info text-sm text-gray">
                工号：{{ employee.employeeNo }} | {{ employee.department }}
              </view>
            </view>
            <view class="employee-status" :class="employee.statusClass">
              {{ employee.statusText }}
            </view>
          </view>
        </view>
        
        <view class="employee-content padding-lr">
          <view class="work-types margin-bottom-sm">
            <text class="text-sm text-gray">掌握工种：</text>
            <view class="work-type-tags">
              <text v-for="workType in employee.workTypes" :key="workType" 
                    class="work-type-tag">{{ workType }}</text>
            </view>
          </view>
          
          <view class="current-task margin-bottom-sm" v-if="employee.currentTask">
            <text class="text-sm text-gray">当前任务：</text>
            <text class="text-sm">{{ employee.currentTask.title }}</text>
            <view class="task-progress margin-top-xs">
              <view class="progress-bar">
                <view class="progress-fill" :style="{ width: employee.currentTask.progress + '%' }"></view>
              </view>
              <text class="text-xs text-gray margin-left-xs">{{ employee.currentTask.progress }}%</text>
            </view>
          </view>
          
          <view class="employee-metrics flex justify-between text-sm">
            <view class="metric-item">
              <text class="metric-label text-gray">本月任务：</text>
              <text class="metric-value text-blue">{{ employee.monthlyTasks }}</text>
            </view>
            <view class="metric-item">
              <text class="metric-label text-gray">完成率：</text>
              <text class="metric-value text-green">{{ employee.completionRate }}%</text>
            </view>
            <view class="metric-item">
              <text class="metric-label text-gray">技能等级：</text>
              <text class="metric-value text-orange">{{ employee.skillLevel }}</text>
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="employee-actions padding">
          <view class="action-buttons flex gap-sm">
            <button v-if="employee.status === 'idle'" 
                    class="cu-btn sm bg-blue" 
                    @click.stop="assignTask(employee)">
              分配任务
            </button>
            <button class="cu-btn sm bg-green line" 
                    @click.stop="viewSkills(employee)">
              技能管理
            </button>
            <button class="cu-btn sm bg-gray line" 
                    @click.stop="editEmployee(employee)">
              编辑
            </button>
            <button class="cu-btn sm bg-red line" 
                    @click.stop="showMoreActions(employee)">
              更多
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredEmployees.length === 0" class="empty-state text-center padding">
      <text class="cuIcon-people text-gray" style="font-size: 120rpx;"></text>
      <view class="text-gray margin-top">暂无员工</view>
    </view>

    <!-- 更多操作弹窗 -->
    <view v-if="showActionModal" class="action-modal" @click="showActionModal = false">
      <view class="action-content" @click.stop>
        <view class="action-header padding">
          <text class="text-lg text-bold">{{ (selectedEmployee && selectedEmployee.name) || '员工' }} - 操作</text>
          <text class="cuIcon-close float-right" @click="showActionModal = false"></text>
        </view>
        <view class="action-list">
          <view class="action-item padding" @click="viewPerformance">
            <text class="cuIcon-chart margin-right text-blue"></text>
            <text>绩效统计</text>
          </view>
          <view class="action-item padding" @click="viewAttendance">
            <text class="cuIcon-calendar margin-right text-green"></text>
            <text>考勤记录</text>
          </view>
          <view class="action-item padding" @click="setLeave">
            <text class="cuIcon-time margin-right text-orange"></text>
            <text>请假设置</text>
          </view>
          <view class="action-item padding" @click="resetPassword">
            <text class="cuIcon-lock margin-right text-purple"></text>
            <text>重置密码</text>
          </view>
          <view class="action-item padding" @click="deleteEmployee">
            <text class="cuIcon-delete margin-right text-red"></text>
            <text>删除员工</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      searchKeyword: '',
      currentFilter: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '工作中', value: 'working' },
        { label: '空闲', value: 'idle' },
        { label: '请假', value: 'leave' }
      ],
      employeeStats: {
        total: 0,
        working: 0,
        idle: 0,
        leave: 0
      },
      employees: [],
      filteredEmployees: [],
      showActionModal: false,
      selectedEmployee: null
    }
  },

  onLoad() {
    this.loadEmployees()
  },

  onPullDownRefresh() {
    this.loadEmployees().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    async loadEmployees() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await mesApi.employee.getList()
        this.employees = response.data.map(employee => ({
          ...employee,
          statusClass: this.calculateStatusClass(employee.status),
          statusText: this.calculateStatusText(employee.status)
        }))
        
        this.calculateStats()
        this.filterEmployees()
        
      } catch (error) {
        console.error('加载员工失败:', error)
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.employees = [
        {
          id: 1,
          name: '张三',
          employeeNo: 'EMP001',
          department: '生产部',
          avatar: '',
          status: 'working',
          workTypes: ['切割', '组装'],
          currentTask: {
            title: '门框切割任务',
            progress: 75
          },
          monthlyTasks: 28,
          completionRate: 95,
          skillLevel: 'A级',
          statusClass: 'status-working',
          statusText: '工作中'
        },
        {
          id: 2,
          name: '李四',
          employeeNo: 'EMP002',
          department: '生产部',
          avatar: '',
          status: 'idle',
          workTypes: ['打包', '质检'],
          currentTask: null,
          monthlyTasks: 25,
          completionRate: 88,
          skillLevel: 'B级',
          statusClass: 'status-idle',
          statusText: '空闲'
        },
        {
          id: 3,
          name: '王五',
          employeeNo: 'EMP003',
          department: '生产部',
          avatar: '',
          status: 'leave',
          workTypes: ['组装', '质检'],
          currentTask: null,
          monthlyTasks: 20,
          completionRate: 92,
          skillLevel: 'A级',
          statusClass: 'status-leave',
          statusText: '请假'
        }
      ]
      
      this.calculateStats()
      this.filterEmployees()
    },

    calculateStats() {
      this.employeeStats = {
        total: this.employees.length,
        working: this.employees.filter(e => e.status === 'working').length,
        idle: this.employees.filter(e => e.status === 'idle').length,
        leave: this.employees.filter(e => e.status === 'leave').length
      }
    },

    calculateStatusClass(status) {
      const statusMap = {
        'working': 'status-working',
        'idle': 'status-idle',
        'leave': 'status-leave'
      }
      return statusMap[status] || 'status-idle'
    },

    calculateStatusText(status) {
      const statusMap = {
        'working': '工作中',
        'idle': '空闲',
        'leave': '请假'
      }
      return statusMap[status] || '空闲'
    },

    onSearch() {
      this.filterEmployees()
    },

    changeFilter(filter) {
      this.currentFilter = filter
      this.filterEmployees()
    },

    filterByStatus(status) {
      this.currentFilter = status
      this.filterEmployees()
    },

    filterEmployees() {
      let filtered = this.employees

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(employee => 
          employee.name.toLowerCase().includes(keyword) ||
          employee.employeeNo.toLowerCase().includes(keyword)
        )
      }

      // 状态过滤
      if (this.currentFilter !== 'all') {
        filtered = filtered.filter(employee => employee.status === this.currentFilter)
      }

      this.filteredEmployees = filtered
    },

    viewEmployeeDetail(employee) {
      uni.navigateTo({
        url: `/pages/production/employee/detail?id=${employee.id}`
      })
    },

    addEmployee() {
      uni.navigateTo({
        url: '/pages/production/employee/add'
      })
    },

    editEmployee(employee) {
      uni.navigateTo({
        url: `/pages/production/employee/edit?id=${employee.id}`
      })
    },

    assignTask(employee) {
      uni.navigateTo({
        url: `/pages/production/task/assign?employeeId=${employee.id}`
      })
    },

    viewSkills(employee) {
      uni.navigateTo({
        url: `/pages/production/employee/skills?id=${employee.id}`
      })
    },

    showMoreActions(employee) {
      this.selectedEmployee = employee
      this.showActionModal = true
    },

    viewPerformance() {
      this.showActionModal = false
      uni.navigateTo({
        url: `/pages/production/employee/performance?id=${this.selectedEmployee.id}`
      })
    },

    viewAttendance() {
      this.showActionModal = false
      uni.navigateTo({
        url: `/pages/production/employee/attendance?id=${this.selectedEmployee.id}`
      })
    },

    setLeave() {
      this.showActionModal = false
      uni.navigateTo({
        url: `/pages/production/employee/leave?id=${this.selectedEmployee.id}`
      })
    },

    resetPassword() {
      this.showActionModal = false
      uni.showModal({
        title: '重置密码',
        content: `确定要重置 ${this.selectedEmployee.name} 的密码吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await mesApi.employee.resetPassword(this.selectedEmployee.id)
              uni.showToast({
                title: '密码重置成功',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    deleteEmployee() {
      this.showActionModal = false
      uni.showModal({
        title: '删除员工',
        content: `确定要删除员工 ${this.selectedEmployee.name} 吗？此操作不可恢复。`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await mesApi.employee.delete(this.selectedEmployee.id)
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadEmployees()
            } catch (error) {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-management-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.stats-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-filter {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 80rpx;
      padding: 0 60rpx 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .search-icon {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
  
  .filter-scroll {
    white-space: nowrap;
    
    .filter-tab-list {
      display: inline-flex;
      
      .filter-tab {
        padding: 16rpx 24rpx;
        margin-right: 16rpx;
        border-radius: 20rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        white-space: nowrap;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.employee-list {
  margin: 0 24rpx;
  
  .employee-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .employee-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
    }
    
    .employee-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 4rpx;
    }
    
    .employee-status {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.status-working {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &.status-idle {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-leave {
        background-color: #f5f5f5;
        color: #999;
      }
    }
    
    .work-type-tags {
      display: inline-flex;
      flex-wrap: wrap;
      gap: 8rpx;
      margin-top: 8rpx;
      
      .work-type-tag {
        padding: 4rpx 12rpx;
        background-color: #e6f7ff;
        color: #1890ff;
        border-radius: 12rpx;
        font-size: 22rpx;
      }
    }
    
    .progress-bar {
      flex: 1;
      height: 6rpx;
      background-color: #f0f0f0;
      border-radius: 3rpx;
      overflow: hidden;
      
      .progress-fill {
        height: 100%;
        background-color: #1890ff;
        transition: width 0.3s ease;
      }
    }
    
    .employee-metrics {
      .metric-item {
        text-align: center;
        
        .metric-label {
          display: block;
          margin-bottom: 4rpx;
        }
        
        .metric-value {
          font-weight: bold;
        }
      }
    }
    
    .action-buttons {
      .cu-btn {
        flex: 1;
        margin-right: 16rpx;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

.action-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .action-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .action-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .action-list {
      .action-item {
        border-bottom: 1rpx solid #f0f0f0;
        display: flex;
        align-items: center;
        font-size: 28rpx;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:active {
          background-color: #f5f5f5;
        }
      }
    }
  }
}

.empty-state {
  margin-top: 120rpx;
}
</style>
